<?php

namespace app\stores\logic\order;



use app\beautiful\logic\ApplyServiceLogic;

use app\beautiful\model\member\MemberOnceCardItemModel;

use app\beautiful\model\member\MemberOnceCardModel;

use app\beautiful\model\member\MemberProjectModel;

use app\beautiful\model\order\OnceCardOrderItemModel;

use app\beautiful\model\order\OnceCardOrderModel;

use app\beautiful\model\project\OnceCardItemModel;

use app\beautiful\model\project\OnceCardModel;

use app\beautiful\model\project\ProjectModel;

use app\beautiful\model\setting\SettingBalanceModel;

use app\beautiful\model\setting\SettingIntegralModel;

use app\beautiful\logic\LogsLogic;

use app\beautiful\logic\MemberWalletLogic;

use app\beautiful\model\member\MemberCouponModel;

use app\common\model\ShopGmvLogsModel;

use app\beautiful\logic\PartnerLogic;



class OrderOnceCardLogic

{

    use OrderTrait;

    protected $once_card;

    protected $order;

    

    public function wxPay($params){

        $this->checkOrderPayStatus($params);

        $this->completePayAct('weixin',$params['payinfo']);

        $MemberWalletLogic = new MemberWalletLogic($this->order->shop_id, $this->order->member_id);

        $MemberWalletLogic->addIntegralByPayment($this->order->need_pay); //更新支付返的积分

        //计算业绩
        $PartnerLogic = new PartnerLogic($this->order->shop_id);
        $PartnerLogic->commissionNew($this->order->member_id,$this->order->need_pay,'onceCardOrder',$this->order->gross);

        //写入GMV

        $shop_gmv_logs = new ShopGmvLogsModel();

        $shop_gmv_logs->shop_id= $this->order->shop_id;

        $shop_gmv_logs->balance= $this->order->need_pay;

        $shop_gmv_logs->save();

    }

    

    public function moneyPay($params)

    {

        //判断订单支付的状态与数据初始化

        $this->checkOrderPayStatus($params);



        //下面是独属于余额支付

        $MemberWalletLogic = new MemberWalletLogic($this->shopId, $this->member->member_id);

        $res = $MemberWalletLogic->useBalance($this->order->need_pay, $this->order->total_price, 15); //商城购物使用

        if($res == false) $this->error($MemberWalletLogic->getError());



        //完成支付后的操作

        $this->completePayAct('money');

        return $this->order->need_pay;

    }

    

    

    public function createOrder($params)

    {

        //判断用户

        empty($params['member_id']) && $this->error('请先登录后再操作');

        $this->checkMember($params['member_id'], false);



        $once_card_id = (int)$params['once_card_id'];

        if ($once_card_id == 0) $this->error('次卡不存在');

        //判断抢购

        $this->checkOnceCard($once_card_id, true);

        if ($this->once_card->is_delete != 0) $this->error('次卡不存在');

        if ($this->once_card->status != 1) $this->error('次卡已下架');



        //秒杀活动时间内判断数量

        if ($flash_status=$this->checkFlashStatus()) {

            if ($this->once_card->flash_num < 1) $this->error('秒杀数量不足够');

        }



        //判断总价

        $total_price=$price = $flash_status ? $this->once_card->flash_price : $this->once_card->price;

        if (empty($params['total_price'])) $this->error('参数错误#1');

        if ((float)$params['total_price'] != $total_price) $this->error('参数错误#2');



        //判断优惠卷

        $coupon_id = $params['coupon_id'] ?? 0;

        $couponBalance = 0;

        if (!empty($coupon_id)) {

            if (null === $myCoupon = MemberCouponModel::find($coupon_id)) $this->error('优惠券不存在');

            if ($myCoupon->status == 1 || $myCoupon->money_limit > $total_price) $this->error('该优惠券不可用');

            if ($myCoupon->member_id != $params['member_id']) $this->error('该优惠券不可用');

            $couponBalance = $myCoupon->coupon_money;

        }



        //判断积分抵扣

        $use_integral = (int)$params['use_integral'];

        if ($use_integral == 1) {

            $integral_balance = $this->getIntegralBalance($total_price);

        }

        $integral = isset($integral_balance) ? $integral_balance['integral'] : 0;

        $balance = isset($integral_balance) ? $integral_balance['balance'] : 0;



        //获取需要支付的金额

        $need_pay = round((($total_price) * 100 - $couponBalance * 100 - $balance * 100) / 100, 2);



        //处理次卡

        $order_model= new OnceCardOrderModel();

        $order_model->save([

            'shop_id'=>$this->shopId,

            'member_id'=>$this->member->member_id,

            'once_card_id'=>$this->once_card->once_card_id,

            'name'=>$this->once_card->name,

            'valid_time'=>$this->once_card->valid_time,

            'valid_unit'=>$this->once_card->valid_unit,

            'is_flash_sale'=>$flash_status ? 1 : 0,

            'cover_img'=>$this->once_card->cover_img,

            'gross'=>$this->once_card->gross,

            'total_price'=>$total_price,

            'member_coupon_id'=>$params['coupon_id'],

            'coupon_money'=>$couponBalance,

            'use_integral'=>$integral,

            'integral_balance'=>$balance,

            'need_pay'=>$need_pay,

            'from_type'=>$params['from_type']

        ]);



        if($flash_status){

            $this->once_card->flash_num=$this->once_card->flash_num-1;

            $this->once_card->fictitious_take_count=$this->once_card->fictitious_take_count+1;

            $this->once_card->take_count=$this->once_card->take_count+1;

            $this->once_card->save();

        }



        //处理次卡项目

        $items=OnceCardItemModel::where([

            ['shop_id','=',$this->shopId],

            ['once_card_id','=',$this->once_card->once_card_id],

            ['is_delete','=',0]

        ])->select()->toArray();

        if(empty($items)) $this->error('次卡错误');



        $item_data=[];

        foreach ($items as $k => $item){

            if(null === $project=ProjectModel::find($item['project_id'])) $this->error('项目不存在');

            if($project->shop_id != $this->shopId) $this->error('项目不存在');

            $item_data[]=[

                'shop_id'=>$this->shopId,

                'member_id'=>$this->member->member_id,

                'once_card_order_id'=>$order_model->once_card_order_id,

                'once_card_item_id'=>$item['once_card_item_id'],

                'project_id'=>$item['project_id'],

                'full_name'=>$project->full_name,

                'abbreviation'=>$project->abbreviation,

                'market_price'=>$project->market_price,

                'cover_img'=>$project->cover_img,

                'total_num'=>$item['num'],

            ];

        }



        $order_item_model=new OnceCardOrderItemModel();

        $order_item_model->saveAll($item_data);



        return $order_model->once_card_order_id;

    }



    public function apply($params)

    {

        //判断其合法性

        $operate_type=(int)$params['operate_type']; $operate_id=(int)$params['operate_id'];

        if(!in_array($operate_type,[1,2])) $this->error('参数错误');



        //判断用户

        $this->checkMember($params['member_id'], false);



        $once_card_id = (int)$params['once_card_id'];

        if ($once_card_id == 0) $this->error('次卡不存在');

        //判断抢购

        $this->checkOnceCard($once_card_id, true);

        if ($this->once_card->is_delete != 0) $this->error('次卡不存在');

        if ($this->once_card->status != 1) $this->error('次卡已下架');



        //秒杀活动时间内判断数量

        if ($flash_status=$this->checkFlashStatus()) {

            if ($this->once_card->flash_num < 1) $this->error('秒杀数量不足够');

        }



        //判断总价

        $total_price=$price = $flash_status ? $this->once_card->flash_price : $this->once_card->price;

        if (empty($params['total_price'])) $this->error('参数错误#1');

        if ((float)$params['total_price'] != $total_price) $this->error('参数错误#2');



        //得到实际支付的金额

        $need_pay=(float)$params['need_pay'];



        //获取优惠金额

        $youhui_balance = round((($total_price) * 100 -$need_pay * 100 ) / 100, 2);

        $youhui_balance = $youhui_balance > 0 ? $youhui_balance : 0;





        //计算有有效时间

        if($this->once_card->valid_unit=='day') $valid_unit=86400;

        if($this->once_card->valid_unit=='month') $valid_unit=86400*30;

        if($this->once_card->valid_unit=='year') $valid_unit=86400*365;

        $valid_end_time=date("Y-m-d",time()+($valid_unit*$this->once_card->valid_time));



        //处理次卡

        $member_once_card_model= new MemberOnceCardModel();

        $member_once_card_model->save([

            'shop_id'=>$this->shopId,

            'member_id'=>$this->member->member_id,

            'once_card_id'=>$this->once_card->once_card_id,

            'name'=>$this->once_card->name,

            'gross'=>$this->once_card->gross,

            'cover_img'=>$this->once_card->cover_img,

            'valid_end_time'=>$valid_end_time,

            'total_price'=>$total_price,

            'need_pay'=>$need_pay,

            'youhui_balance'=>$youhui_balance,

            'pay_type'=>'offline',

            'pay_time'=>time(),

        ]);



        if($flash_status){

            $this->once_card->flash_num=$this->once_card->flash_num-1;

            $this->once_card->fictitious_take_count=$this->once_card->fictitious_take_count+1;

            $this->once_card->take_count=$this->once_card->take_count+1;

            $this->once_card->save();

        }



        //处理次卡项目

        $items=OnceCardItemModel::where([

            ['shop_id','=',$this->shopId],

            ['once_card_id','=',$this->once_card->once_card_id],

            ['is_delete','=',0]

        ])->select()->toArray();

        if(empty($items)) $this->error('次卡错误');





        foreach ($items as $k => $item){

            //添加项目销量

            if(null === $project=ProjectModel::find($item['project_id'])) $this->error('项目不存在');

            if($project->shop_id != $this->shopId) $this->error('项目不存在');

            $project->take_count = $project->take_count + $item['num'];

            $project->save();



            $item_data=[

                'shop_id'=>$this->shopId,

                'member_id'=>$this->member->member_id,

                'member_once_card_id'=>$member_once_card_model->member_once_card_id,

                'project_id'=>$item['project_id'],

                'full_name'=>$project->full_name,

                'abbreviation'=>$project->abbreviation,

                'market_price'=>$project->market_price,

                'cover_img'=>$project->cover_img,

                'total_num'=>$item['num'],

                'remain_num'=>$item['num'],

            ];

            $member_item_model = new MemberOnceCardItemModel();

            $member_item_model->save($item_data);



            //处理我的项目

            $member_project_data=[

                'shop_id'=>$this->shopId,

                'member_id'=>$this->member->member_id,

                'source'=>'once_card',

                'project_id'=>$project->project_id,

                'member_once_card_item_id'=>$member_item_model->member_once_card_item_id,

                'total_num'=>$item['num'],

                'remain_num'=>$item['num'],

                'valid_end_time'=>$valid_end_time,

            ];

            $member_project_model=new MemberProjectModel();

            $member_project_model->save($member_project_data);

        }



        //添加办卡记录

        $res=ApplyServiceLogic::apply($this->shopId,$this->member->member_id,'once_card',$this->once_card->name,$member_once_card_model->member_once_card_id,$need_pay,$total_price,$operate_type,$operate_id);

        if(!$res) $this->error('办理失败');

        return $this->once_card->gross;



    }



    public function sendOnceCard($params)

    {

        //判断用户

        $this->checkMember($params['member_id'], false);



        $once_card_id = (int)$params['once_card_id'];

        if ($once_card_id == 0) $this->error('次卡不存在');

        //判断抢购

        $this->checkOnceCard($once_card_id, true);

        if ($this->once_card->is_delete != 0) $this->error('次卡不存在');

        if ($this->once_card->status != 1) $this->error('次卡已下架');



        //秒杀活动时间内判断数量

        $flash_status=$this->checkFlashStatus();



        //判断总价

        $total_price=$price = $flash_status ? $this->once_card->flash_price : $this->once_card->price;



        //得到实际支付的金额

        $need_pay=0;



        //获取优惠金额

        $youhui_balance = round((($total_price) * 100 -$need_pay * 100 ) / 100, 2);

        $youhui_balance = $youhui_balance > 0 ? $youhui_balance : 0;





        //计算有有效时间

        if($this->once_card->valid_unit=='day') $valid_unit=86400;

        if($this->once_card->valid_unit=='month') $valid_unit=86400*30;

        if($this->once_card->valid_unit=='year') $valid_unit=86400*365;

        $valid_end_time=date("Y-m-d",time()+($valid_unit*$this->once_card->valid_time));



        //处理次卡

        $member_once_card_model= new MemberOnceCardModel();

        $member_once_card_model->save([

            'shop_id'=>$this->shopId,

            'member_id'=>$this->member->member_id,

            'once_card_id'=>$this->once_card->once_card_id,

            'name'=>$this->once_card->name,

            'cover_img'=>$this->once_card->cover_img,

            'valid_end_time'=>$valid_end_time,

            'total_price'=>$total_price,

            'need_pay'=>$need_pay,

            'youhui_balance'=>$youhui_balance,

            'pay_type'=>'offline',

            'pay_time'=>time(),

        ]);



        //处理次卡项目

        $items=OnceCardItemModel::where([

            ['shop_id','=',$this->shopId],

            ['once_card_id','=',$this->once_card->once_card_id],

            ['is_delete','=',0]

        ])->select()->toArray();

        if(empty($items)) $this->error('次卡错误');





        foreach ($items as $k => $item){

            //添加项目销量

            if(null === $project=ProjectModel::find($item['project_id'])) $this->error('项目不存在');

            if($project->shop_id != $this->shopId) $this->error('项目不存在');



            $item_data=[

                'shop_id'=>$this->shopId,

                'member_id'=>$this->member->member_id,

                'member_once_card_id'=>$member_once_card_model->member_once_card_id,

                'project_id'=>$item['project_id'],

                'full_name'=>$project->full_name,

                'abbreviation'=>$project->abbreviation,

                'market_price'=>$project->market_price,

                'cover_img'=>$project->cover_img,

                'total_num'=>$item['num'],

                'remain_num'=>$item['num'],

            ];

            $member_item_model = new MemberOnceCardItemModel();

            $member_item_model->save($item_data);



            //处理我的项目

            $member_project_data=[

                'shop_id'=>$this->shopId,

                'member_id'=>$this->member->member_id,

                'source'=>'once_card',

                'project_id'=>$project->project_id,

                'member_once_card_item_id'=>$member_item_model->member_once_card_item_id,

                'total_num'=>$item['num'],

                'remain_num'=>$item['num'],

                'valid_end_time'=>$valid_end_time,

            ];

            $member_project_model=new MemberProjectModel();

            $member_project_model->save($member_project_data);

        }



        //添加办卡记录

        $res=ApplyServiceLogic::apply($this->shopId,$this->member->member_id,'once_card',$this->once_card->name,$member_once_card_model->member_once_card_id,$need_pay,$total_price,0,0);

        if(!$res) $this->error('办理失败');

    }



    



    public function cancelOrder($params)

    {

        //判断用户

        empty($params['member_id']) && $this->error('请先登录后再操作');

        $this->checkMember($params['member_id'], false);



        //判断传来的订单

        $once_card_order_id = (int)$params['once_card_order_id'];

        $this->checkOrder($once_card_order_id, true);

        if ($this->order->member_id != $this->member->member_id) $this->error('订单不存在');

        if ($this->order->is_paid != 0) $this->error('订单不存在');

        if ($this->order->is_delete == 1) $this->error('订单不在未支付状态');



        //判断抢购

        $this->checkOnceCard($this->order->once_card_id,true);



        //处理订单

        $this->order->is_delete = 1;

        $this->order->save();



        //如果是秒杀取消就释放库存

        if($this->order->is_flash_sale==1){

            $this->once_card->flash_num=$this->once_card->flash_num+1;

            $this->once_card->fictitious_take_count=$this->once_card->fictitious_take_count-1 > 0 ? $this->once_card->fictitious_take_count-1 : 0;

            $this->once_card->take_count=$this->once_card->take_count-1;

            $this->once_card->save();

        }

    }





    protected function completePayAct($type,$payinfo = [])

    {

        $this->order->is_paid = 1;

        $this->order->is_delete = 1;

        $this->order->pay_time = time();

        $this->order->pay_type = $type;

        $this->order->pay_info = $payinfo;

        $this->order->save();



        //如果不是秒杀这时候要去添加销量

        if($this->order->is_flash_sale==0){

            $this->once_card->fictitious_take_count=$this->once_card->fictitious_take_count+1;

            $this->once_card->take_count=$this->once_card->take_count+1;

            $this->once_card->save();

        }



        //计算有有效时间

        if($this->order->valid_unit=='day') $valid_unit=86400;

        if($this->order->valid_unit=='month') $valid_unit=86400*30;

        if($this->order->valid_unit=='year') $valid_unit=86400*365;

        $valid_end_time=date("Y-m-d",time()+($valid_unit*$this->order->valid_time));





        //处理我的次卡

        $member_once_data_data=[

            'shop_id'=>$this->shopId,

            'member_id'=>$this->member->member_id,

            'once_card_order_id'=>$this->order->once_card_order_id,

            'once_card_id'=>$this->once_card->once_card_id,

            'name'=>$this->order->name,

            'cover_img'=>$this->order->cover_img,

            'valid_end_time'=>$valid_end_time,

            'market_price'=>$this->order->market_price,

            'total_price'=>$this->order->total_price,

            'member_coupon_id'=>$this->order->member_coupon_id,

            'coupon_money'=>$this->order->coupon_money,

            'use_integral'=>$this->order->use_integral,

            'integral_balance'=>$this->order->integral_balance,

            'youhui_balance'=>$this->order->youhui_balance,

            'need_pay'=>$this->order->need_pay,

            'pay_type'=>$this->order->pay_type,

            'pay_time'=>$this->order->pay_time,

            'pay_info'=>$this->order->pay_info,

        ];

        $member_once_card_model=new MemberOnceCardModel();

        $member_once_card_model->save($member_once_data_data);



        //处理我的次卡项目

        $items=OnceCardOrderItemModel::where([

            ['shop_id','=',$this->shopId],

            ['once_card_order_id','=',$this->order->once_card_order_id],

        ])->select()->toArray();

        if(empty($items)) $this->error('订单出错啦');



        foreach ($items as $k => $item){

            //处理次卡项目

            $item_data=[

                'shop_id'=>$this->shopId,

                'member_id'=>$this->member->member_id,

                'member_once_card_id'=>$member_once_card_model->member_once_card_id,

                'project_id'=>$item['project_id'],

                'full_name'=>$item['full_name'],

                'abbreviation'=>$item['abbreviation'],

                'market_price'=>$item['market_price'],

                'cover_img'=>$item['cover_img'],

                'total_num'=>$item['total_num'],

                'remain_num'=>$item['total_num'],

            ];

            $member_item_model = new MemberOnceCardItemModel();

            $member_item_model->save($item_data);





            //添加项目销量

            if(null === $project=ProjectModel::find($item['project_id'])) $this->error('项目不存在');

            if($project->shop_id != $this->shopId) $this->error('项目不存在');

            $project->take_count = $project->take_count + $item['total_num'];

            $project->save();



            //处理我的项目

            $member_project_data=[

                'shop_id'=>$this->shopId,

                'member_id'=>$this->member->member_id,

                'source'=>'once_card',

                'project_id'=>$project->project_id,

                'member_once_card_item_id'=>$member_item_model->member_once_card_item_id,

                'total_num'=>$item['total_num'],

                'remain_num'=>$item['total_num'],

                'valid_end_time'=>$valid_end_time,

            ];

            $member_project_model=new MemberProjectModel();

            $member_project_model->save($member_project_data);

        }



        //添加办卡记录

        $res=ApplyServiceLogic::apply($this->shopId,$this->member->member_id,'once_card',$this->order->name,$member_once_card_model->member_once_card_id,$this->order->need_pay,$this->order->total_price,0,0);

        if(!$res) $this->error('支付失败');





    }





    protected function checkOrderPayStatus($params)

    {

        //判断用户

        empty($params['member_id']) && $this->error('请先登录后再操作');

        $this->checkMember($params['member_id'], false);



        //判断传来的订单

        $once_card_order_id = (int)$params['once_card_order_id'];

        $this->checkOrder($once_card_order_id, true);

        if ($this->order->member_id != $this->member->member_id) $this->error('订单不存在');

        if ($this->order->is_paid != 0) $this->error('订单不存在');

        if ($this->order->is_delete == 1) $this->error('订单不在未支付状态');

        if($this->order->add_time < (time() - 900)) $this->error('订单支付已经超时了，不能继续支付');



        //判断抢购

        $this->checkOnceCard($this->order->once_card_id,true);





        //处理数据

        if(!empty($this->order->member_coupon_id)){

            if(null === $myCoupon = MemberCouponModel::find($this->order->member_coupon_id)) $this->error('优惠券不存在');

            if($myCoupon->status == 1) $this->error('优惠券不存在');



            $myCoupon->status = 1;

            $myCoupon->save();

            LogsLogic::coupon($this->shopId, $this->member->member_id, -1, 15, $this->order->member_coupon_id, '', 0);

        }

        $MemberWalletLogic = new MemberWalletLogic($this->shopId, $this->member->member_id);

        if(!empty($order->use_integral)){ //使用积分

            $res = $MemberWalletLogic->useIntegral($order->use_integral, 12);

            if($res == false) $this->error($MemberWalletLogic->getError());

        }

        $needPay = round(($this->order->total_price * 100 - $this->order->coupon_money * 100 - $this->order->integral_balance * 100)/100,2);

        if($needPay <= 0 or $needPay!=$this->order->need_pay)  $this->error('支付金额不正确');

    }





    protected function checkOnceCard($once_card_id,$lock)

    {

        if(null === $this->once_card = OnceCardModel::lock($lock)->find($once_card_id)) $this->error('次卡不存在');

        if($this->once_card->shop_id != $this->shopId) $this->error('次卡不存在');

    }



    protected function checkOrder($once_card_order_id,$lock)

    {

        if(null === $this->order = OnceCardOrderModel::lock($lock)->find($once_card_order_id))  $this->error('订单不存在');

        if($this->order->shop_id != $this->shopId) $this->error('订单不存在');

    }



    protected function checkFlashStatus()

    {

        return ($this->once_card->is_flash_sale == 1 && $this->once_card->is_flash_sale_expire == 0);

    }





    public function getIntegralBalance($total_price)

    {

        $SettingBalance = SettingBalanceModel::where([['shop_id', '=', $this->shopId]])->find();

        if (null === $SettingBalance) {

            $integral_deduction_balance_limit_rate = 0;

        } else {

            $integral_deduction_balance_limit_rate = $SettingBalance->integral_deduction_balance_limit_rate; //积分抵扣的比率 百分比

        }

        $integralSetting = SettingIntegralModel::where([['shop_id', '=', $this->shopId]])->find();

        if ($integralSetting === null) { //如果是空 代表不使用积分抵扣余额

            $integral_exchange_balance = 0;

        } else {

            $integral_exchange_balance = $integralSetting->integral_exchange_balance;//汇率

        }



        $pre_can_exchange_balance = round(($total_price * ($integral_deduction_balance_limit_rate * 100)) / 10000, 2);

        $pre_can_exchange_integral = $integral_exchange_balance == 0 ? 0 : round(($pre_can_exchange_balance * 10000) / ($integral_exchange_balance * 100), 0);

        $member_integral = $this->member->integral;

        if ($member_integral >= $pre_can_exchange_integral) {

            $return = [

                'integral' => $pre_can_exchange_integral,

                'balance' => $pre_can_exchange_balance

            ];

        } else {

            $return = [

                'integral' => $member_integral,

                'balance' => round(($member_integral * ($integral_exchange_balance * 100)) / 10000, 2),

            ];

        }

        return $return;



    }

}